

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:kmxy_base/widget/grid_list_view.dart';
import 'package:kmxy_base/widget/size_reporter.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

typedef TableViewContentBuilder = List<Widget> Function(
    BuildContext context, int index, dynamic itemData);
typedef TableViewCreatedCallback = void Function(
    TableViewController controller);

class TableView extends StatefulWidget {
  // 标题view列表
  final List<Widget> titleList;
  // 数据内容view回调
  final TableViewContentBuilder contentList;
  // 数据
  final List dataList;
  // TableView 的高度
  final double tableViewHeight;
  //分割线
  final Divider? divider;

  final bool enablePullDown;
  final bool enablePullUp;

  final OnRefresh? onRefresh;
  final OnLoading? onLoading;
  final TableViewCreatedCallback onTableViewCreated;
  final Widget? noDataView;

  const TableView({
    required this.onTableViewCreated,
    required this.titleList,
    required this.contentList,
    required this.dataList,
    required this.tableViewHeight,
    this.divider,
    this.enablePullDown = true,
    this.enablePullUp = true,
    this.onRefresh,
    this.onLoading,
    this.noDataView,
    Key? key,
  }) : super(key: key);

  @override
  _TableViewState createState() => _TableViewState();
}

class _TableViewState extends State<TableView> {
  double titleWidth = 0;
  double titleHeight = 0;
  RefreshController refreshController = RefreshController();

  bool isLoading = false;

  @override
  void dispose() {
    refreshController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      scrollDirection: Axis.horizontal,
      child: Column(
        children: [
          SizeReporter(
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: widget.titleList,
            ),
            call: (width, height) {
              setState(() {
                titleWidth = width;
                titleHeight = height;
              });
            },
          ),
          SizedBox(
            width: titleWidth,
            height: widget.tableViewHeight - titleHeight,
            child: SmartRefresher(
              enablePullDown: widget.enablePullDown,
              enablePullUp: widget.enablePullUp,
              header: const WaterDropHeader(
                complete: Text("数据刷新"),
                failed: Text("没有数据了"),
              ),
              footer: CustomFooter(
                builder: (BuildContext context, LoadStatus? mode) {
                  Widget body;
                  if (mode == LoadStatus.idle) {
                    body = const Text("上拉加载");
                  } else if (mode == LoadStatus.loading) {
                    body = const CupertinoActivityIndicator();
                  } else if (mode == LoadStatus.failed) {
                    body = const Text("加载失败,点击重试");
                  } else if (mode == LoadStatus.canLoading) {
                    body = const Text("松手,加载更多");
                  } else {
                    body = const Text("没有更多数据了");
                  }
                  return SizedBox(
                    height: 55,
                    child: Center(child: body),
                  );
                },
              ),
              controller: refreshController,
              onRefresh: widget.onRefresh,
              onLoading: widget.onLoading,
              child: widget.dataList.isEmpty
                  ? (widget.noDataView ??
                      Container(
                        alignment: Alignment.center,
                        child: Text(isLoading ? '加载中...' : '没有数据'),
                      ))
                  : ListView.separated(
                      itemCount: widget.dataList.length,
                      separatorBuilder: (context, index) =>
                          widget.divider ?? Container(),
                      itemBuilder: (BuildContext context, int index) => Row(
                        mainAxisSize: MainAxisSize.min,
                        children: widget.contentList(
                            context, index, widget.dataList[index]),
                      ),
                    ),
            ),
          ),
        ],
      ),
    );
  }

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((mag) {
      widget.onTableViewCreated(TableViewController(refreshController, this));
    });
    super.initState();
  }

  setIsLoading(bool loadingState) {
    setState(() {
      isLoading = loadingState;
    });
  }
}

class TableViewController {
  late RefreshController refreshController;
  late _TableViewState viewState;

  TableViewController(RefreshController controller, _TableViewState state) {
    refreshController = controller;
    viewState = state;
    viewState.setIsLoading(true);
  }

  /// true 没有更多数据
  onFinishLoading(bool isNoData) {
    if (isNoData) {
      refreshController.loadNoData();
    } else {
      refreshController.loadComplete();
    }
    viewState.setIsLoading(false);
  }

  onFinishRefresh() {
    refreshController.loadComplete();
    refreshController.refreshCompleted();
    viewState.setIsLoading(false);
  }

  setIsLoading(bool loadingState) {
    viewState.setIsLoading(loadingState);
  }
}
